#!/bin/bash

# 默认配置参数
PG_USER="pguser"
PG_PASS="pgpassword"
PG_DB="pgdb"
PG_PORT=5432

MARIADB_ROOT_PASS="mariadbrootpass"
MARIADB_USER="mariadbuser"
MARIADB_PASS="mariadbpassword"
MARIADB_DB="mariadbdemo"
MARIADB_PORT=3306

REDIS_PORT=6379
REDIS_PASS="redispwd"

# 显示菜单
show_menu() {
echo "==================================================================="
echo "        🔧 请选择要执行的操作（输入数字）                         "
echo "        1) 安装 PostgreSQL                                         "
echo "        2) 安装 MariaDB                                            "
echo "        3) 安装 Redis                                              "
echo "        4) 安装全部                                                "
echo "        5) 卸载所选数据库（谨慎操作，请提前备份）                  "
echo "==================================================================="
}

# 安装 PostgreSQL
install_postgresql() {
    echo "🐘 正在安装 PostgreSQL..."
    apt install -y postgresql postgresql-contrib > /dev/null 2>&1
    systemctl enable postgresql > /dev/null 2>&1
    systemctl start postgresql > /dev/null 2>&1

    sudo -u postgres psql -c "CREATE USER $PG_USER WITH PASSWORD '$PG_PASS';" > /dev/null 2>&1
    sudo -u postgres psql -c "CREATE DATABASE $PG_DB OWNER $PG_USER;" > /dev/null 2>&1

    echo ""
    echo "✅ PostgreSQL 安装完成"
    echo "   地址: localhost"
    echo "   端口: $PG_PORT"
    echo "   用户名: $PG_USER"
    echo "   密码: $PG_PASS"
    echo "   数据库: $PG_DB"
}

# 安装 MariaDB
install_mariadb() {
    echo "🗄️ 正在安装 MariaDB..."

    export DEBIAN_FRONTEND=noninteractive
    apt install -y mariadb-server > /dev/null 2>&1

    mysqladmin -u root password "$MARIADB_ROOT_PASS" > /dev/null 2>&1

    mysql -u root -p"$MARIADB_ROOT_PASS" -e "CREATE DATABASE IF NOT EXISTS $MARIADB_DB;" \
          -e "CREATE USER IF NOT EXISTS '$MARIADB_USER'@'localhost' IDENTIFIED BY '$MARIADB_PASS';" \
          -e "GRANT ALL PRIVILEGES ON $MARIADB_DB.* TO '$MARIADB_USER'@'localhost';" \
          -e "FLUSH PRIVILEGES;" > /dev/null 2>&1

    systemctl enable mariadb > /dev/null 2>&1
    systemctl start mariadb > /dev/null 2>&1

    echo ""
    echo "✅ MariaDB 安装完成"
    echo "   地址: localhost"
    echo "   端口: $MARIADB_PORT"
    echo "   用户名: $MARIADB_USER"
    echo "   密码: $MARIADB_PASS"
    echo "   数据库: $MARIADB_DB"
    echo "   Root 密码: $MARIADB_ROOT_PASS"
}

# 安装 Redis
install_redis() {
    echo ".Redis 正在安装中..."

    apt install -y redis-server > /dev/null 2>&1

    sed -i 's/bind 127.0.0.1 ::1/bind 127.0.0.1/' /etc/redis/redis.conf
    sed -i 's/protected-mode no/protected-mode yes/' /etc/redis/redis.conf
    echo "requirepass $REDIS_PASS" >> /etc/redis/redis.conf

    systemctl enable redis > /dev/null 2>&1
    systemctl start redis > /dev/null 2>&1

    echo ""
    echo "✅ Redis 安装完成"
    echo "   地址: localhost"
    echo "   端口: $REDIS_PORT"
    echo "   密码: $REDIS_PASS"
    echo "   仅限本地访问，默认未启用远程访问，请手动修改配置文件。"
}

# 卸载数据库
uninstall_dbs() {
    read -p "⚠️ 警告：此操作将删除所选数据库及其所有数据！请确认是否已备份？(y/n): " confirm
    if [[ "$confirm" != "y" ]]; then
        echo "❌ 操作取消。"
        exit 1
    fi

    echo "🔧 开始卸载所选数据库..."

    if [ "$install_pg" == "1" ]; then
        echo "🗑️ 卸载 PostgreSQL..."
        systemctl stop postgresql > /dev/null 2>&1
        apt purge -y postgresql* > /dev/null 2>&1
        rm -rf /etc/postgresql/
        echo "✅ PostgreSQL 已卸载"
    fi

    if [ "$install_mariadb" == "1" ]; then
        echo "🗑️ 卸载 MariaDB..."
        systemctl stop mariadb > /dev/null 2>&1
        apt purge -y mariadb-server > /dev/null 2>&1
        rm -rf /etc/mysql/
        echo "✅ MariaDB 已卸载"
    fi

    if [ "$install_redis" == "1" ]; then
        echo "🗑️ 卸载 Redis..."
        systemctl stop redis > /dev/null 2>&1
        apt purge -y redis-server > /dev/null 2>&1
        rm -rf /etc/redis/
        echo "✅ Redis 已卸载"
    fi

    echo "🎉 所选数据库已成功卸载！"
}

# 主程序逻辑
main() {
    show_menu
    read -p "请输入选项 (1-5): " choice

    case $choice in
        1)
            install_postgresql
            ;;
        2)
            install_mariadb
            ;;
        3)
            install_redis
            ;;
        4)
            install_postgresql
            install_mariadb
            install_redis
            ;;
        5)
            echo "🔧 进入卸载模式，请再次选择要卸载的数据库（多个用空格分隔，例如：1 2 3）"
            echo "        1) PostgreSQL"
            echo "        2) MariaDB"
            echo "        3) Redis"
            echo "        4) 全部"
            read -p "请输入要卸载的选项: " -a choices

            for c in "${choices[@]}"; do
                case $c in
                    1) install_pg=1 ;;
                    2) install_mariadb=1 ;;
                    3) install_redis=1 ;;
                    4) install_pg=1; install_mariadb=1; install_redis=1 ;;
                    *) echo "❌ 无效选项: $c"; exit 1 ;;
                esac
            done

            uninstall_dbs
            ;;
        *)
            echo "❌ 无效选项！"
            exit 1
            ;;
    esac
}

main